package com.ceba.test.modules.admin.helper;

import abc.ID;
import com.ceba.base.helper.LoggerHelper;
import com.ceba.base.stamp.StampFontFactory;
import com.ceba.base.utils.IDSDateUtils;
import com.ceba.cebautils.DateUtil;
import com.ceba.cebautils.StringUtil;
import com.ceba.test.base.config.LogicPathUtil;
import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.enums.StampTypeEnum;
import com.ceba.test.base.language.ResourceUtils;
import com.ceba.test.modules.admin.entity.GStamp;
import com.ceba.test.modules.admin.logicService.AdminLogicService;
import com.ceba.test.modules.storage.logicService.StorageFileCacheManage;
import com.ceba.test.modules.usermanage.entity.UUser;
import com.ceba.test.modules.usermanage.logicService.UserManageLogicService;
import configs.context.SpringBeans;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GStampHelper {

	static Logger logger = LoggerFactory.getLogger(GStampHelper.class);
	
	private static AdminLogicService adminLogicService = SpringBeans.getAdminLogicService("adminLogicService");
	
	private static UserManageLogicService userManageLogicService = SpringBeans.getUserManageLogicService("userManageLogicService");
	/**
	 * 获取水印地址
	 * @return
	 */	
	public static GStamp getWatermark(String qianWaterId,String waterType) {
		return adminLogicService.getWatermark(qianWaterId, waterType);
	}
	

	public static GStamp getUserGStampById(String id){
		GStamp gs = new GStamp();
		gs.setId(id);
		try {
			List<GStamp> stampList= adminLogicService.getUserGStampById(id);
			if(stampList !=null && stampList.size()>0){
				GStamp myStamp = stampList.get(0);
				GStamp.parseFrontOtherStamp(myStamp,gs);
				gs.setUserHtml("<span>"+myStamp.getName()+
						"</span><input id='txtUserID' type='hidden' value=\""+myStamp.getUserId()+"\"/>");
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return gs;
	}
	
	
	/**
	 * 获取所有用户的ID
	 * @param 
	 * @return
	 */
	public static GStamp getUserIds(){
		GStamp gs = new GStamp();
		String userHtml = "";
		try {
			List<UUser> users = userManageLogicService.getUserIds();
			if(users!=null && users.size()>0){
				userHtml="<select id='txtUserID' onchange='userChange()'>";
				for (UUser user:users) {
					if(!StringUtil.isEmptyString(user.getName())){
						userHtml+="<option value=\""+user.getId()+"\">"+user.getName()+"</option>";
					}
				}
				userHtml+="</select>";
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		gs.setUserHtml(userHtml);
		return gs;
	}
	
	public static GStamp getUserIdsNotInStamp(){
		GStamp gs = new GStamp();
		String userHtml = "";
		try {
			List<UUser> users = userManageLogicService.getUserIdsNotInStamp();
			if(users!=null && users.size()>0){
				userHtml="<select id='txtUserID' onchange='userChange()'>";
				for (UUser user:users) {
					if(!StringUtil.isEmptyString(user.getName())){
						userHtml+="<option value=\""+user.getId()+"\">"+user.getName()+"</option>";
					}
				}
				userHtml+="</select>";
			}
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		gs.setUserHtml(userHtml);
		return gs;
	}
	
	/**
	 * 根据id获取报告章
	 * @param stampID
	 * @return
	 */
	public static GStamp getCorStampByStampId(String stampID){
		GStamp gs = new GStamp();
		try {
			gs = adminLogicService.getCorStampObjectByStampId(stampID);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		
		return gs;
		
	}
	
	/**
	 * 根据id获取章
	 * @param stampId
	 * @return
	 */
	public static GStamp getStampById(String stampId){
		GStamp gs = new GStamp();
		try {
			gs = adminLogicService.getStampById(stampId);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		
		return gs;
	}
	
	public static String getUserStampHtml(String userId) throws Exception{
		String html="";
		String stampIds="",stampid="";
		List<GStamp> stampList= adminLogicService.getUserStampDTByUserId(userId);
			
			if(stampList!=null && stampList.size()>0){
				for (GStamp row :stampList) {
					stampid=row.getId();
					if(stampIds.indexOf(stampid)<0){
						html+="<option value=\""+row.getId()+"\">"+row.getCorStampName()+"</option>";
						stampIds+=stampid+";";
				}
			}
		
		
		}
		return html;
	}
	
	public static boolean isUserStampShow(String userId) throws Exception{
		List<GStamp> stampList= adminLogicService.getUserStampDTByUserId(userId);
			
		if(stampList!=null &&stampList.size()>1){
			return true;
		}else{
			return false;
		}
			
	}
	
	public static String getUserRole(String userId ){
		String role="";
		try {
			return userManageLogicService.getUserRoleByUserId(userId);
		} catch (Exception e) {
			LoggerHelper.error(logger, e, "");
		}
		return role;
	}
	
	
	
	/**
	 * 根据id获取章对象  (CMA接口调用)
	 * @return
	 * @throws Exception
	 */
	public static List<GStamp> getStampsListByIds(Map<String, Object> paramMap)throws Exception{
		
		 List<GStamp> gs= adminLogicService.getStampsListByIds(paramMap);
		 //封装日期章   骑缝章    水印  对象
		 if(gs==null ){
			 gs=new ArrayList<GStamp>();
		 }else{
			 //添加骑缝章
			 List<GStamp> gsQf= adminLogicService.getStampsQiFengListByIds(paramMap);
			 gs.addAll(gsQf);
		 }
		 
		 //添加日期章
		 String DATE_TYPE = CebaConfig.CUSTOM_DATE_FORMAT;
		 GStamp data= searchDateStamp(CebaConfig.ANDMIN_USER_ID,DATE_TYPE);
		 gs.add(data);

		 //添加自定义日期图片
		String dateName=(String)paramMap.get("dateName");
		String dateContent=(String)paramMap.get("dateContent");
		//只有这两个都存在才生成图片并保存在图片列表中
		if(org.apache.commons.lang3.StringUtils.isNotBlank(dateName) && org.apache.commons.lang3.StringUtils.isNotBlank(dateContent)){
			GStamp customData=createCustomDateStamp(dateName,dateContent);
			gs.add(customData);
		}

		 //添加审批意见
		 List<GStamp> examineStamps= queryExamineStamp();
		 gs.addAll(examineStamps);
		 
		return gs;
	}

	private static GStamp createCustomDateStamp(String dateName,String dateContent){
		String userId=CebaConfig.ANDMIN_USER_ID;
		String storageId = StorageFileCacheManage.getSystemUseAddressId();
		LogicPathUtil.getPhysicalPicDirPath(storageId,userId);//创建目录
		String dir=LogicPathUtil.getVirtualPicDirPath(userId);
		String uuid=ID.getGuid();
		String filePath=dir+uuid+".png";//章(虚拟路径)
        createDateImage(storageId,filePath,"0",dateContent);//永远创建图片
		GStamp stamp=new GStamp();
		stamp.setCorStampName(dateName);
		stamp.setId(uuid);
		stamp.setImgWidth("75");
		stamp.setImgHeight("14");
		stamp.setFilePath(filePath);
		stamp.setCorFlag(StampTypeEnum.CREDIENTAL_COR_DATE_STAMP_FLAG.getType());
		stamp.setUserId(userId);
		stamp.setMatchName("");
		stamp.setFilePath(LogicPathUtil.getBrowserPath(storageId,stamp.getFilePath()));
		return stamp;
	}
	
	/**
	 * 获取审批章
	 */
	
	public  static List<GStamp> queryExamineStamp(){
		List<GStamp> list = new ArrayList<GStamp>();
		//获取同意图片章
		GStamp stamp=new GStamp();
		stamp.setCorStampName(ResourceUtils.getMessage("REST_EXAMINE_STAMP_AGREE"));
		stamp.setId(ID.getGuid());
		stamp.setImgWidth("442");
		stamp.setImgHeight("300");
		stamp.setFilePath(LogicPathUtil.getBrowserPath(StorageFileCacheManage.getSystemUseAddressId(),LogicPathUtil.getExaminePicPath("agree.png")));
		stamp.setCorFlag(StampTypeEnum.USER_COR_EXAMINE_STAMP_FLAG.getType());
		stamp.setUserId(CebaConfig.ANDMIN_USER_ID);
		stamp.setMatchName("");
		list.add(stamp);
		
		GStamp stamp1=new GStamp();
		stamp1.setCorStampName(ResourceUtils.getMessage("REST_EXAMINE_STAMP_DISAGREE"));
		stamp1.setId(ID.getGuid());
		stamp1.setImgWidth("630");
		stamp1.setImgHeight("300");
		stamp1.setFilePath(LogicPathUtil.getBrowserPath(StorageFileCacheManage.getSystemUseAddressId(),LogicPathUtil.getExaminePicPath("disagree.png")));
		stamp1.setCorFlag(StampTypeEnum.USER_COR_EXAMINE_STAMP_FLAG.getType());
		stamp1.setUserId(CebaConfig.ANDMIN_USER_ID);
		stamp1.setMatchName("");
		list.add(stamp1);
		
		return list;
	}
	
	
	/**
	 * 根据id获取章对象  (自定义签名数据加载使用)
	 * @return
	 * @throws Exception
	 */
	
	public static List<GStamp> getCustomStampsListByIds(Map<String, Object> paramMap)throws Exception{
		 List<GStamp> gs= adminLogicService.getStampsListByIds(paramMap);
		return gs;
	}
	
	

	
	
	
	/**
	 * 创建日期章
	 *
	 */
	public static synchronized GStamp searchDateStamp(String userid,String dateType) throws Exception{
		GStamp stamp=adminLogicService.getUserStampObjectByUserID(userid);
		String storageId = StorageFileCacheManage.getSystemUseAddressId();
		LogicPathUtil.getPhysicalPicDirPath(storageId,userid);
		if(stamp == null){
			//为管理员插入一个时间章
			stamp=new GStamp();
			stamp.setCorStampName(ResourceUtils.getMessage("REST_DATA_STAMP"));
			stamp.setId(ID.getGuid());
			stamp.setImgWidth("75");
			stamp.setImgHeight("14");
			String dir=LogicPathUtil.getVirtualPicDirPath(userid);
			String filePath=dir+ID.getGuid()+".png";//章(虚拟路径)
			String nowDateStr=DateUtil.getNowTime(dateType);
			createDateImage(storageId,filePath,null,nowDateStr);
			stamp.setFilePath(filePath);
			stamp.setCorFlag(StampTypeEnum.CREDIENTAL_COR_DATE_STAMP_FLAG.getType());
			stamp.setUserId(userid);
			stamp.setMatchName("");

			try {
				adminLogicService.addStamp(stamp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{

			String nowDateStr=DateUtil.getNowTime(dateType);
			if(stamp.getUpdateTime()!=null){
				String pastDateStr= IDSDateUtils.dateStr(stamp.getUpdateTime(),DateUtil.YYYY_MM_DD_HH_MM_SS,dateType);
				createDateImage(storageId,stamp.getFilePath(),pastDateStr,nowDateStr);
				if(!(StringUtils.equals(nowDateStr, pastDateStr))){
					stamp.setCorStampName("日期");
					adminLogicService.updateStamp(stamp);
				}
			}else {
				createDateImage(storageId,stamp.getFilePath(),null,nowDateStr);
				stamp.setCorStampName("日期");
				adminLogicService.updateStamp(stamp);
			}

		}
		stamp.setFilePath(LogicPathUtil.getBrowserPath(storageId,stamp.getFilePath()));
		return stamp;
	}

	/**
	 * 创建日期章
	 *
	 */
	public static synchronized GStamp searchDateStampWithCustomDate(String userid,String dateType, String dateContent) throws Exception{
		GStamp stamp=adminLogicService.getUserStampObjectByUserID(userid);
		String storageId = StorageFileCacheManage.getSystemUseAddressId();
		LogicPathUtil.getPhysicalPicDirPath(storageId,userid);

		String nowDateStr = null;
		if (null == dateContent || dateContent.isEmpty()) {
			nowDateStr = DateUtil.getNowTime(dateType);
		} else {
			nowDateStr = dateContent;
		}

		if(stamp == null){
			//为管理员插入一个时间章
			stamp=new GStamp();
			stamp.setCorStampName(ResourceUtils.getMessage("REST_DATA_STAMP"));
			stamp.setId(ID.getGuid());
			stamp.setImgWidth("75");
			stamp.setImgHeight("14");
			String dir=LogicPathUtil.getVirtualPicDirPath(userid);
			String filePath=dir+ID.getGuid()+".png";//章(虚拟路径)
			createDateImage(storageId,filePath,null,nowDateStr);
			stamp.setFilePath(filePath);
			stamp.setCorFlag(StampTypeEnum.CREDIENTAL_COR_DATE_STAMP_FLAG.getType());
			stamp.setUserId(userid);
			stamp.setMatchName("");

			try {
				adminLogicService.addStamp(stamp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			if(stamp.getUpdateTime()!=null){
				String pastDateStr= IDSDateUtils.dateStr(stamp.getUpdateTime(),DateUtil.YYYY_MM_DD_HH_MM_SS,dateType);
				createDateImage(storageId,stamp.getFilePath(),pastDateStr,nowDateStr);
				if(!(StringUtils.equals(nowDateStr, pastDateStr))){
					stamp.setCorStampName("日期");
					adminLogicService.updateStamp(stamp);
				}
			}else {
				createDateImage(storageId,stamp.getFilePath(),null,nowDateStr);
				stamp.setCorStampName("日期");
				adminLogicService.updateStamp(stamp);
			}
		}
		stamp.setFilePath(LogicPathUtil.getBrowserPath(storageId,stamp.getFilePath()));
		return stamp;
	}


	//创建日期图片
	private static String createDateImage(String storageId,String filePath,String pastDateStr,String nowDateStr) {
		String pathPic =LogicPathUtil.getSystemUploadPath(storageId)+filePath;
		File file = new File(pathPic);
		if(!file.exists() || !(StringUtils.equals(nowDateStr, pastDateStr))){
			StampFontFactory.createDateStamp(pathPic,nowDateStr);
			//StampFontFactory.createDateStamp(pathPic,nowDateStr); //字体是HANG_YAN_WEN
			StampFontFactory.createDateStamp(pathPic,nowDateStr, StampFontFactory.FontFimilyEnum.fromCode(CebaConfig.CUSTOM_DATE_FONT));//指定字体
		}
		return filePath;
	}
}
